package com.hctg.forced2sleep.utils;

import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Build;
import android.util.ArrayMap;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;

import androidx.annotation.NonNull;

import com.actor.myandroidframework.utils.ConfigUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.hctg.forced2sleep.service.MyAccessibilityService;
import com.hjq.window.EasyWindow;

/**
 * description: 描述
 * company    :
 *
 * @author : ldf
 * date       : 2024/5/30 on 21
 * @version 1.0
 */
public class FloatViewUtils {

    public  static ArrayMap<String, View> viewMap = new ArrayMap<>();

    /**
     * 获取辅助功能服务的 WindowManager
     * @return
     */
    public static WindowManager getWindowManager() {
        WindowManager windowManager = null;
        //                                              22
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            // 使用无障碍的上下文获取 WindowManager
            MyAccessibilityService myAccessibilityService = MyAccessibilityService.get();
            if (myAccessibilityService != null) {
                windowManager = (WindowManager) myAccessibilityService.getSystemService(Context.WINDOW_SERVICE);
            }
        }
        if (windowManager == null) {
            windowManager = (WindowManager) ConfigUtils.APPLICATION.getSystemService(Context.WINDOW_SERVICE);
        }
        return windowManager;
    }

    /**
     * 获取全局悬浮窗的 WindowManager
     * @return
     */
    public static WindowManager getAppWindowManager() {
        return EasyWindow.with(ConfigUtils.APPLICATION).getWindowManager();
    }


    /**
     * 显示悬浮窗
     * @param touchAble 显示的View是否可触摸
     * @param isWidthMatchParent 宽度是否全屏
     * @param isHeightMatchParent 高度是否全屏
     *                            if宽高都是全屏, gravity=↖, 否则gravity=Center
     */
    public static WindowManager.LayoutParams getLayoutParams(boolean touchAble,
                                                             boolean isWidthMatchParent,
                                                             boolean isHeightMatchParent) {
        boolean isRunning = AccessibilityUtils.isAccessibilitySettingsOn(MyAccessibilityService.class);

        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();

        //                                              22
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1 && isRunning) {
            //全局的悬浮窗
            layoutParams.type = WindowManager.LayoutParams.TYPE_ACCESSIBILITY_OVERLAY;
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {    //26
            layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY;
            //系统窗口，例如低电量警告弹窗，在应用窗口之上。
//            layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
            //电话窗口，这是非应用窗口，用于来电的界面，该窗口通常置于所有应用之上，但在状态栏下。
//            layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
            //透明通知，不会拦截触摸事件，可以向下透传。
//            layoutParams.type = WindowManager.LayoutParams.TYPE_TOAST;
        }

        layoutParams.width = isWidthMatchParent ? WindowManager.LayoutParams.MATCH_PARENT : WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.height = isHeightMatchParent ? ScreenUtils.getScreenHeight() : WindowManager.LayoutParams.WRAP_CONTENT;
//        layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;  //底部导航栏会显示出来
//        layoutParams.height = ScreenUtils.getScreenHeight();            //高度全屏, 包括导航栏
        //if设置不可触摸, 则底部按钮可触摸(但还是锁住的)
//        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
        if (!touchAble) {
//            layoutParams.flags = 16778008;
            layoutParams.flags = WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED   //16777216
                    | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS                  //     512, 允许窗口扩展到屏幕之外
                    | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN                  //     256, 忽略父窗口中的任何约束
                    | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE                     //      16
                    | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;                    //       8
        } else if (Build.VERSION.SDK_INT >= 19) {
//            layoutParams.flags = 201328136; //201328136-134217728-67108864-1024-512-8
            layoutParams.flags = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_FULLSCREEN        //
                    | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
                    | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        } else {
//            layoutParams.flags = 1544;  //1024+512+8
            layoutParams.flags = WindowManager.LayoutParams.FLAG_FULLSCREEN
                    | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
                    | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        }

        //                              28
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            //是否在刘海区域内显示内容
//            layoutParams.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
            // - 在竖屏模式和横屏模式下，内容都会呈现到刘海区域中。
            layoutParams.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
        }

        //设置图片格式，效果为背景透明
//        layoutParams.format = PixelFormat.RGBA_8888;
        layoutParams.format = PixelFormat.TRANSLUCENT;
//        layoutParams.alpha = 1.0f;
        layoutParams.gravity = (isWidthMatchParent && isHeightMatchParent) ? Gravity.TOP | Gravity.LEFT : Gravity.CENTER;



        return layoutParams;
    }

    public static LayoutInflater getLayoutInflater() {
        boolean isRunning = AccessibilityUtils.isAccessibilitySettingsOn(MyAccessibilityService.class);
        LayoutInflater mInflater;
        if (isRunning) {
            MyAccessibilityService service = MyAccessibilityService.get();
            mInflater = (LayoutInflater) service.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        } else {
            mInflater = (LayoutInflater) ConfigUtils.APPLICATION.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        return mInflater;
    }

//    /**
//     * 显示锁屏View
//     */
//    public static View showLockScreenView() {
//        WindowManager.LayoutParams layoutParams = getLayoutParams(true);
//        LayoutAccessBinding viewBinding = LayoutAccessBinding.inflate(getLayoutInflater());
//        viewBinding.btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
////                service.startActivity(new Intent(service, MainActivity.class));
//
//                removeView(viewBinding.getRoot());
//            }
//        });
//        viewBinding.tv.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                WindowManager.LayoutParams layoutParams1 = FloatViewUtils.getLayoutParams(true);
//                layoutParams1.width = WindowManager.LayoutParams.WRAP_CONTENT;
//                layoutParams1.height = WindowManager.LayoutParams.WRAP_CONTENT;
//                layoutParams1.gravity = Gravity.CENTER;
//                DialogAccessibilityOpenTipsBinding viewBinding = DialogAccessibilityOpenTipsBinding.inflate(getLayoutInflater());
//                addView(viewBinding.getRoot(), layoutParams1);
//                viewBinding.ivClose.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        removeView(viewBinding.getRoot());
//                    }
//                });
//            }
//        });
//        addView(viewBinding.getRoot(), layoutParams);
//        return viewBinding.getRoot();
//    }

    /**
     * 添加View
     * @param view
     * @param layoutParams {@link #getLayoutParams(boolean,boolean,boolean)}
     */
    public static void addView(View view, WindowManager.LayoutParams layoutParams) {
        if (view == null) return;
        //可在子线程中.addView()
        getWindowManager().addView(view, layoutParams);
        viewMap.put(getViewKey(view), view);
    }

    public static void removeView(View view) {
        if (view == null) return;
        View view2 = viewMap.remove(getViewKey(view));
        if (view2 != null) {
//            view2.setVisibility(View.GONE);
            try {
                //重复remove会报错
                getWindowManager().removeView(view2);  //异步删除
                //同步删除, WindowManagerGlobal.checkThread检查当前线程是不是创建view的线程，是的话再在ViewRootImpl进行删除view处理
//                getWindowManager().removeViewImmediate(view2);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    protected static String getViewKey(@NonNull View view) {
        return view.getClass().getName() + view.hashCode();
    }
}
